package com.yuanqi.service.impl;

import com.yuanqi.domain.OrderPayment;
import com.yuanqi.domain.PaymentApplicationRequest;
import com.yuanqi.repository.OrderPaymentRepository;
import com.yuanqi.service.OrderPaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderPaymentServiceImpl implements OrderPaymentService {

    @Autowired
    private OrderPaymentRepository orderPaymentRepository;

    @Override
    public Page<OrderPayment> getOrderPayments(Pageable pageable, String orderType, String orderNumber, String paymentStatus) {
        // 如果pageable为null，创建默认分页
        if (pageable == null) {
            pageable = PageRequest.of(0, 10);
        }

        // 如果有查询条件，使用自定义查询
        if (orderType != null || orderNumber != null || paymentStatus != null) {
            List<OrderPayment> orders = getOrderPaymentsByConditions(orderType, orderNumber, paymentStatus);
            // 这里需要手动分页，简化处理
            return Page.empty(pageable);
        }

        return orderPaymentRepository.findAll(pageable);
    }

    @Override
    public OrderPayment getOrderPaymentById(Integer id) {
        return orderPaymentRepository.findById(id).orElse(null);
    }

    @Override
    public OrderPayment getOrderPaymentByOrderNumber(String orderNumber) {
        return orderPaymentRepository.findByOrderNumber(orderNumber).orElse(null);
    }

    @Override
    @Transactional
    public Map<String, Object> applyPayment(PaymentApplicationRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 验证订单是否存在
            OrderPayment order = getOrderPaymentById(request.getOrderId());
            if (order == null) {
                result.put("success", false);
                result.put("message", "订单不存在");
                return result;
            }

            // 2. 验证付款金额
            if (request.getAmount().compareTo(order.getPendingAmount()) > 0) {
                result.put("success", false);
                result.put("message", "付款金额超过待付款金额");
                return result;
            }

            // 3. 验证订单状态
            if (order.getPaymentStatus() == OrderPayment.STATUS_PAID) {
                result.put("success", false);
                result.put("message", "订单已全额付款，无需再次申请");
                return result;
            }

            // 4. 更新订单付款申请状态
            order.setApplicationStatus(OrderPayment.APPLICATION_STATUS_APPLIED);
            order.setApplicationAmount(request.getAmount());
            order.setApplicationTime(LocalDateTime.now());
            order.setApplicant(request.getApplicant() != null ? request.getApplicant() : "admin");
            order.setPaymentMethod(request.getPaymentMethod());
            order.setPaymentDate(request.getPaymentDate());
            order.setUpdateTime(LocalDateTime.now());

            // 5. 保存更新
            orderPaymentRepository.save(order);

            result.put("success", true);
            result.put("message", "付款申请提交成功");
            result.put("paymentId", order.getId());

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> createOrder(Map<String, Object> orderData) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 数据验证
            if (orderData == null) {
                result.put("success", false);
                result.put("message", "订单数据不能为空");
                return result;
            }

            // 验证必填字段
            String orderNumber = (String) orderData.get("orderNumber");
            String orderType = (String) orderData.get("orderType");
            String orderDate = (String) orderData.get("orderDate");
            String supplierName = (String) orderData.get("supplierName");
            String responsiblePerson = (String) orderData.get("responsiblePerson");
            String contactPhone = (String) orderData.get("contactPhone");
            Object totalAmountObj = orderData.get("totalAmount");
            Object pendingAmountObj = orderData.get("pendingAmount");

            if (orderNumber == null || orderNumber.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "订单编号不能为空");
                return result;
            }

            if (orderType == null || orderType.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "订单类型不能为空");
                return result;
            }

            if (orderDate == null || orderDate.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "订单日期不能为空");
                return result;
            }

            if (supplierName == null || supplierName.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "供应商名称不能为空");
                return result;
            }

            if (responsiblePerson == null || responsiblePerson.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "负责人不能为空");
                return result;
            }

            if (contactPhone == null || contactPhone.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "联系电话不能为空");
                return result;
            }

            if (totalAmountObj == null) {
                result.put("success", false);
                result.put("message", "总金额不能为空");
                return result;
            }

            if (pendingAmountObj == null) {
                result.put("success", false);
                result.put("message", "待付款金额不能为空");
                return result;
            }

            // 创建新的OrderPayment实体
            OrderPayment newOrder = new OrderPayment();

            // 设置基本信息
            newOrder.setOrderNumber(orderNumber.trim());
            newOrder.setOrderType("采购单".equals(orderType) ?
                OrderPayment.ORDER_TYPE_PURCHASE : OrderPayment.ORDER_TYPE_RETURN);

            try {
                newOrder.setOrderDate(java.time.LocalDate.parse(orderDate));
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "订单日期格式错误，请使用YYYY-MM-DD格式");
                return result;
            }

            newOrder.setSupplierCustomerName(supplierName.trim());
            newOrder.setContactPerson(responsiblePerson.trim());
            newOrder.setContactPhone(contactPhone.trim());

            try {
                BigDecimal totalAmount = new java.math.BigDecimal(totalAmountObj.toString());
                BigDecimal pendingAmount = new java.math.BigDecimal(pendingAmountObj.toString());

                newOrder.setTotalAmount(totalAmount);
                newOrder.setPendingAmount(pendingAmount);
                // 设置amount字段（等于totalAmount）
                newOrder.setAmount(totalAmount);
            } catch (NumberFormatException e) {
                result.put("success", false);
                result.put("message", "金额格式错误，请输入有效的数字");
                return result;
            }

            newOrder.setPaidAmount(java.math.BigDecimal.ZERO);
            newOrder.setPaymentStatus(OrderPayment.STATUS_UNPAID);
            newOrder.setStatus(OrderPayment.STATUS_UNPAID);

            String remark = (String) orderData.get("remark");
            newOrder.setRemark(remark != null ? remark.trim() : "");

            String creator = (String) orderData.get("creator");
            newOrder.setCreatorName(creator != null ? creator.trim() : "admin");
            newOrder.setCreatedBy(1); // 默认创建者ID
            newOrder.setCreateTime(java.time.LocalDateTime.now());
            newOrder.setUpdateTime(java.time.LocalDateTime.now());

            // 保存到数据库
            OrderPayment savedOrder = orderPaymentRepository.save(newOrder);

            result.put("success", true);
            result.put("message", "订单创建成功");
            result.put("orderId", savedOrder.getId());
            result.put("order", savedOrder);

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建订单失败：" + e.getMessage());
            // 记录详细错误日志
            System.err.println("创建订单详细错误: {}"+ e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, Object> getOrderPaymentStats() {
        Map<String, Object> stats = new HashMap<>();

        try {
            long totalOrders = orderPaymentRepository.count();
            long unpaidOrders = orderPaymentRepository.countByPaymentStatus(OrderPayment.STATUS_UNPAID);
            long partialPaidOrders = orderPaymentRepository.countByPaymentStatus(OrderPayment.STATUS_PARTIAL);
            long paidOrders = orderPaymentRepository.countByPaymentStatus(OrderPayment.STATUS_PAID);

            stats.put("totalOrders", totalOrders);
            stats.put("unpaidOrders", unpaidOrders);
            stats.put("partialPaidOrders", partialPaidOrders);
            stats.put("paidOrders", paidOrders);

            // 这里应该计算总金额和待付款金额，简化处理
            stats.put("totalAmount", 1250000.00);
            stats.put("pendingAmount", 450000.00);

        } catch (Exception e) {
            stats.put("error", "获取统计数据失败：" + e.getMessage());
        }

        return stats;
    }

    @Override
    public List<OrderPayment> getOrderPaymentsByConditions(String orderType, String orderNumber, String paymentStatus) {
        Integer orderTypeInt = null;
        Integer paymentStatusInt = null;

        if (orderType != null && !orderType.isEmpty()) {
            orderTypeInt = "purchase".equals(orderType) ? OrderPayment.ORDER_TYPE_PURCHASE : OrderPayment.ORDER_TYPE_RETURN;
        }

        if (paymentStatus != null && !paymentStatus.isEmpty()) {
            switch (paymentStatus) {
                case "unpaid":
                    paymentStatusInt = OrderPayment.STATUS_UNPAID;
                    break;
                case "partial":
                    paymentStatusInt = OrderPayment.STATUS_PARTIAL;
                    break;
                case "paid":
                    paymentStatusInt = OrderPayment.STATUS_PAID;
                    break;
            }
        }

        return orderPaymentRepository.findByConditions(orderTypeInt, orderNumber, paymentStatusInt);
    }

    @Override
    @Transactional
    public Map<String, Object> approvePayment(Integer orderId, String approver, String approveRemark) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 验证订单是否存在
            OrderPayment order = getOrderPaymentById(orderId);
            if (order == null) {
                result.put("success", false);
                result.put("message", "订单不存在");
                return result;
            }

            // 2. 验证申请状态
            if (order.getApplicationStatus() != OrderPayment.APPLICATION_STATUS_APPLIED) {
                result.put("success", false);
                result.put("message", "订单状态不正确，无法审批");
                return result;
            }

            // 3. 更新审批状态
            order.setApplicationStatus(OrderPayment.APPLICATION_STATUS_APPROVED);
            order.setUpdateTime(LocalDateTime.now());

            // 4. 执行付款（更新付款状态）
            BigDecimal newPaidAmount = order.getPaidAmount().add(order.getApplicationAmount());
            BigDecimal newPendingAmount = order.getPendingAmount().subtract(order.getApplicationAmount());

            if (newPendingAmount.compareTo(BigDecimal.ZERO) <= 0) {
                order.setPaymentStatus(OrderPayment.STATUS_PAID);
                order.setPendingAmount(BigDecimal.ZERO);
                order.setApplicationStatus(OrderPayment.APPLICATION_STATUS_PAID);
            } else {
                order.setPaymentStatus(OrderPayment.STATUS_PARTIAL);
                order.setPendingAmount(newPendingAmount);
            }

            order.setPaidAmount(newPaidAmount);

            // 5. 保存更新
            orderPaymentRepository.save(order);

            result.put("success", true);
            result.put("message", "付款审批通过");
            result.put("orderId", order.getId());

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "审批失败：" + e.getMessage());
        }

        return result;
    }

    @Override
    @Transactional
    public Map<String, Object> rejectPayment(Integer orderId, String rejector, String rejectRemark) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 验证订单是否存在
            OrderPayment order = getOrderPaymentById(orderId);
            if (order == null) {
                result.put("success", false);
                result.put("message", "订单不存在");
                return result;
            }

            // 2. 验证申请状态
            if (order.getApplicationStatus() != OrderPayment.APPLICATION_STATUS_APPLIED) {
                result.put("success", false);
                result.put("message", "订单状态不正确，无法驳回");
                return result;
            }

            // 3. 重置申请状态
            order.setApplicationStatus(OrderPayment.APPLICATION_STATUS_NOT_APPLIED);
            order.setApplicationAmount(BigDecimal.ZERO);
            order.setApplicationTime(null);
            order.setApplicant(null);
            order.setPaymentMethod(null);
            order.setPaymentDate(null);
            order.setUpdateTime(LocalDateTime.now());

            // 4. 保存更新
            orderPaymentRepository.save(order);

            result.put("success", true);
            result.put("message", "付款申请已驳回");
            result.put("orderId", order.getId());

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "驳回失败：" + e.getMessage());
        }

        return result;
    }
}
